from django.contrib.auth.hashers import make_password
from rest_framework import serializers
from bookshop.models import UserInfo, UserType, Book, Types, UserBlack, UserBook, UserHistory, UserCollection


class UserBookModelSerializer(serializers.ModelSerializer):
    """用户书架 序列化器"""
    user = serializers.StringRelatedField()

    class Meta:
        model = UserBook
        fields = '__all__'


class UserHistoryModelSerializer(serializers.ModelSerializer):
    """用户借阅历史 序列化器"""
    user = serializers.StringRelatedField()

    class Meta:
        model = UserHistory
        fields = '__all__'


class UserCollectionModelSerializer(serializers.ModelSerializer):
    """用户收藏 序列化器"""
    user = serializers.StringRelatedField()

    class Meta:
        model = UserCollection
        fields = '__all__'


class UserModelSerializer(serializers.ModelSerializer):
    """用户 序列化器"""
    # 1.转换字段声明   #(如果模型中没有的话，可以直接在此处写一个)
    types = serializers.StringRelatedField()
    blacklist = serializers.StringRelatedField()
    userinfo_userbooks = UserBookModelSerializer(many=True, read_only=False, required=False)  # 将书架中的书以列表字典属性返回
    userinfo_UserHistory = UserBookModelSerializer(many=True, read_only=False, required=False)
    userinfo_UserCollection = UserBookModelSerializer(many=True, read_only=False, required=False)
    # 2.如果当前序列化器继承的是modelserializer，则需要声明调用的模型信息    # required=Falase 书架可以为空，待添加
    # 必须个Meta声明两个属性
    class Meta:
        model = UserInfo  # 模型，必填
        fields = "__all__"  # 字段列表，必填

        # read_only_fields=[]  #选填 只读字段列表，只有序列化阶段才会用到
        # extra_kwargs={} #选填，字段额外选项声明


class TypesUserSerializer(serializers.ModelSerializer):
    """用户类型"""
    type_user = UserModelSerializer(many=True, read_only=False)  #

    class Meta:
        model = UserType
        fields = '__all__'


class UserBlackSerializer(serializers.ModelSerializer):
    """用户状态"""
    black_user = UserModelSerializer(many=True, read_only=False)

    class Meta:
        model = UserBlack
        fields = '__all__'


# """嵌套序列化器关联"""
# 效果就是学生的反向外键成为了具体的数据信息，而不是单独以指定字段或方式进行维护定义的
class BookModelSerializer(serializers.ModelSerializer):
    """图书"""
    types = serializers.StringRelatedField()  # 将关联表的***str***方法作为结果返回

    class Meta:
        model = Book
        fields = '__all__'


class TypesSerializer(serializers.ModelSerializer):
    """与BookModelSerializer关联的序列化器。
    新加序列化的属性types_books，获取与类型对应的图书集合
    """
    types_books = BookModelSerializer(many=True, read_only=False, required=False)  #将对应的图书作为属性返回

    class Meta:
        model = Types
        fields = '__all__'
